package com.baizhi.util;

import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
 * @author 王雪洋
 * @Time 2017年4月29日 下午1:09:42
 * @disc: 该类主要用于MyBatis常用基本功能封装
 */
public class MyBatisUtil {
	private  static SqlSessionFactory factory;
	//创建线程绑定Sqlsession
	private static final ThreadLocal<SqlSession> tl = new ThreadLocal<SqlSession>();
	//加载必要的配置文件
	static{
		try {
			//使用resources 流  加载MyBatis 的核心配置文件
			InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
			//创建sqlsession的工厂
			factory = new SqlSessionFactoryBuilder().build(is);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	//通过工厂创建SqlSession对象
	public static SqlSession openSession(){
		SqlSession session = tl.get();
		if(session == null){
			session = factory.openSession();
			tl.set(session);
		}
		return session;
	}
	//关闭sqlsession资源
	private static void closeSession(){
		SqlSession session = factory.openSession();
		session.close();
		tl.remove();
	}
	//提交事务
	public static void commit(){
		SqlSession session = openSession();
		session.commit();
		closeSession();
	}
	//回滚事务
	public static void rollback(){
		SqlSession session = openSession();
		session.rollback();
		closeSession();
	}
	//获得接口实现类对象
	public static <T> T getMapper(Class<T> clazz){
		SqlSession session = openSession();
		return session.getMapper(clazz);
	}
}
